package com.supinfo.suptracking.dao.jpa;

import com.supinfo.suptracking.dao.GpsPositionHistoryDao;
import com.supinfo.suptracking.entity.Car;
import com.supinfo.suptracking.entity.Gpspositionhistory;
import com.supinfo.suptracking.entity.Gpspositionhistory_;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Fabien, Jérémy, Ludovic, Brice
 */

@Stateless
public class JpaGpsPositionHistoryDao implements GpsPositionHistoryDao{

    @PersistenceContext
    private EntityManager em;
    
    @Override
    public void addPositionHistory(Gpspositionhistory positionHistory) {
        em.persist(positionHistory);
    }

    @Override
    public void delPositionHistory(Gpspositionhistory positionHistory) {
        Long id = positionHistory.getId();
        em.remove(id);
    }

    @Override
    public void delPositionHistory(Long id) {
        em.remove(id);
    }

    @Override
    public List<Gpspositionhistory> getAllPositionHistory(String longitude, String latitude) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Gpspositionhistory> query = cb.createQuery(Gpspositionhistory.class);
        return em.createQuery(query).getResultList();
    }

    @Override
    public List<Gpspositionhistory> getAllPositionHistoryByCar(Car car) {
        
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Gpspositionhistory> query = cb.createQuery(Gpspositionhistory.class);
        Root<Gpspositionhistory> gpsposhist = query.from(Gpspositionhistory.class);
        
        List<Predicate> predicates = new ArrayList<>();
        predicates.add(cb.equal(gpsposhist.get(Gpspositionhistory_.car), car));
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getResultList();
    }

    @Override
    public List<Gpspositionhistory> getAllPositionHistoryByDate(Date date) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Gpspositionhistory> query = cb.createQuery(Gpspositionhistory.class);
        Root<Gpspositionhistory> gpsposhist = query.from(Gpspositionhistory.class);
        
        List<Predicate> predicates = new ArrayList<>();
        predicates.add(cb.equal(gpsposhist.get(Gpspositionhistory_.date), date));
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getResultList();
    }
}
